package com.tang.starter.config;

import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.Schema;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.customizers.DelegatingMethodParameterCustomizer;
import org.springdoc.core.customizers.PropertyCustomizer;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author tang jun liang
 * @Date 2023/9/2 21:12
 */
@Component
@Primary
public class CoolPropertyCustomizer implements PropertyCustomizer {


    @SneakyThrows
    @Override
    public Schema customize(Schema property, AnnotatedType type) {
        if (StringUtils.isBlank(property.get$ref())) {
            return property;
        }
        Class<?> clazz;
        try {
            clazz = Class.forName(property.get$ref());
        } catch (Exception e) {
            return property;
        }
        if (!Enum.class.isAssignableFrom(clazz)) {
            return property;
        }
        Object[] enumConstants = clazz.getEnumConstants();
        List<String> displayValues = Arrays.stream(enumConstants).map(item -> {
            try {
                Method getDesc = clazz.getDeclaredMethod("getDesc");
                getDesc.setAccessible(true);
                Method getValue = clazz.getDeclaredMethod("getValue");
                getValue.setAccessible(true);
                return getValue.invoke(item) + "-" + getDesc.invoke(item);
            } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
        String enumDescText = "(" + String.join("; ", displayValues) + ")";
        Schema newProperty = new Schema();
//        BeanUtils.copyProperties(property, newProperty);
        if (StringUtils.isBlank(property.getDescription())) {
            newProperty.setDescription("状态：" + enumDescText);
        } else {
            newProperty.setDescription(property.getDescription() + "：" + enumDescText);
        }
        newProperty.setType("string");
        newProperty.setName(property.getName());
        Json.pretty(newProperty);
        return newProperty;
    }
}
